package org.goldfish.library_system.service;

import org.goldfish.library_system.entity.Book;
import org.goldfish.library_system.repos.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {
    @Autowired
    private BookRepository bookRepository;

    // 获取所有图书
    public List<Book> findAllBooks() {
        return bookRepository.findAll();
    }

    // 根据 ID 获取图书
    public Optional<Book> findBookById(Long id) {
        return bookRepository.findById(id);
    }

    // 添加或更新图书
    public Book saveBook(Book book) {
        return bookRepository.save(book);
    }

    // 删除图书
    public void deleteBook(Long id) {
        bookRepository.deleteById(id);
    }

    // 更新库存数量
    public Book updateStock(Long bookId, int delta) {
        Optional<Book> optionalBook = bookRepository.findById(bookId);
        if (optionalBook.isPresent()) {
            Book book = optionalBook.get();
            book.setStock(book.getStock() + delta);
            return bookRepository.save(book);
        }
        throw new IllegalArgumentException("Book not found with ID: " + bookId);
    }
}